<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Socket</title>
    <script type="text/javascript">
        var websocket;

        //如果浏览器支持WebSocket  {appKey}/{sign}/{account}/{channel}/{version}/{deviceId}
        if(window.WebSocket){
            websocket = new WebSocket("ws://localhost:9328/ws/ad36ea5238504216ae3ca471780b1225/4517328874ef7b1a8b1ec2776e2fb8ba/UZ202101232152071569589662543872/channel/version/deviceId");  //获得WebSocket对象

            //当有消息过来的时候触发
            websocket.onmessage = function(event){
                var respMessage = document.getElementById("respMessage");
                respMessage.value = respMessage.value + "\n" + event.data;
                heartCheck.start();
            }

            //连接关闭的时候触发
            websocket.onclose = function(event){
                var respMessage = document.getElementById("respMessage");
                respMessage.value = respMessage.value + "\n断开连接";
            }

            //连接打开的时候触发
            websocket.onopen = function(event){
                var respMessage = document.getElementById("respMessage");
                respMessage.value = "建立连接";
                heartCheck.start();
            }
        }else{
            alert("浏览器不支持WebSocket");
        }

        function sendMsg(msg) { //发送消息
            if(window.WebSocket){
                if(websocket.readyState == WebSocket.OPEN) { //如果WebSocket是打开状态
                    websocket.send(msg); //send()发送消息
                }
            }else{
                return;
            }
        }
        //心跳检测
        var heartCheck = {
            timeout: 3000,
            timeoutObj: null,
            serverTimeoutObj: null,
            start: function(){
                console.log('start');
                var self = this;
                this.timeoutObj && clearTimeout(this.timeoutObj);
                this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
                this.timeoutObj = setTimeout(function(){
                    //这里发送一个心跳，后端收到后，返回一个心跳消息，
                    console.log('心跳');
                    websocket.send("[{\"cmd\":2,\"cmdCode\":\"\",\"body\":\"心跳\"}]");
                    self.serverTimeoutObj = setTimeout(function() {
                        console.log(websocket);
                        websocket.close();
                        // createWebSocket();
                    }, self.timeout);

                }, this.timeout)
            }
        }
    </script>
</head>
<body>
<form onsubmit="return false">
    <textarea style="width: 300px; height: 200px;" name="message"></textarea>
    <input type="button" onclick="sendMsg(this.form.message.value)" value="发送"><br>
    <h3>信息</h3>
    <textarea style="width: 300px; height: 200px;" id="respMessage"></textarea>
    <input type="button" value="清空" onclick="javascript:document.getElementById('respMessage').value = ''">
</form>
</body>
</html>